package com.enation.app.javashop.core.goods.service.impl;

import com.enation.app.javashop.core.base.model.dto.FileDTO;
import com.enation.app.javashop.core.base.model.vo.FileVO;
import com.enation.app.javashop.core.base.service.FileManager;
import com.enation.app.javashop.core.goods.model.dos.GoodsDO;
import com.enation.app.javashop.core.goods.model.enums.SharePageType;
import com.enation.app.javashop.core.goods.model.vo.PlacardGenVO;
import com.enation.app.javashop.core.goods.service.GoodsQueryManager;
import com.enation.app.javashop.core.goods.service.GoodsShareManager;
import com.enation.app.javashop.core.payment.plugin.weixin.signaturer.WechatSignaturer;
import com.enation.app.javashop.core.payment.plugin.weixin.signaturer.WechatTypeEnmu;
import com.enation.app.javashop.core.promotion.tool.model.enums.PromotionTypeEnum;
import com.enation.app.javashop.core.promotion.tool.model.vo.PromotionVO;
import com.enation.app.javashop.core.promotion.tool.service.PromotionGoodsManager;
import com.enation.app.javashop.core.system.enums.WeixinMiniproConstants;
import com.enation.app.javashop.framework.cache.Cache;
import com.enation.app.javashop.framework.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class GoodsShareManagerImpl  implements GoodsShareManager {

    @Autowired
    private WechatSignaturer wechatSignaturer;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private Cache cache;
    @Autowired
    private FileManager fileManager;
    @Autowired
    private GoodsQueryManager goodsQueryManager;
    @Autowired
    private PromotionGoodsManager promotionGoodsManager;

    private final String codeUrl = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=";

    @Override
    public Map<String, Object> gen(PlacardGenVO vo) {
        Map<String,Object>  resultMap = new HashMap<>();
        if(StringUtil.isEmpty(vo.getScene())){
            throw new RuntimeException("scene参数不能为空");
        }
        if(StringUtil.isEmpty(vo.getPagePath())){
            throw new RuntimeException("pagePath不能为空");
        }

        Map<String,Object> params = new HashMap<>();
        params.put("scene",vo.getScene());
        params.put("page",vo.getPagePath());
        if (vo.getWidth() != null){
            params.put("width",vo.getWidth());
        }
        if(vo.isHyaline()){
            params.put("isHyaline",true);
        }
        if(vo.isAutoColor()){
            params.put("isAutoColor",true);
        }

        //获取太阳码的地址
        String sunCodeUrl = this.doPostWithJson(codeUrl+this.getAccessToken(),params);
        resultMap.put("sun_code_url",sunCodeUrl);

        // 如果是商品详情页分享，则获取商品详情的对应的图片、价格等相关的信息
        if(vo.getPageType() == SharePageType.GOODS_DETAIL.getValue().intValue()){
            // 查询商品
            GoodsDO goodsDO = goodsQueryManager.getModel(vo.getQueryId());
            resultMap.put("master_pic",goodsDO.getOriginal());      //商品原图路径
            resultMap.put("price",goodsDO.getPrice());              //商品价格
            resultMap.put("goods_name",goodsDO.getGoodsName());     //商品名称
            resultMap.put("mktprice",goodsDO.getMktprice());        //商品市场价格
            // 查询促销价格
            List<PromotionVO> promotionVOList = this.promotionGoodsManager.getPromotion(goodsDO.getGoodsId());
            for (PromotionVO promotionVO : promotionVOList) {
                if(promotionVO.getPromotionType().equals(PromotionTypeEnum.SECKILL.name())){
                    resultMap.put("price",promotionVO.getSeckillGoodsVO().getSeckillPrice());
                }
                if(promotionVO.getPromotionType().equals(PromotionTypeEnum.SHETUAN.name())){
                    resultMap.put("price",promotionVO.getShetuanGoodsVO().getShetuanPrice());
                }
            }
            if(goodsDO.getMktprice()==null){
                log.debug("划线价为空");
            }else{
                log.debug("划线价为："+goodsDO.getMktprice());
            }
            resultMap.put("selling",goodsDO.getSelling());              //商品卖点
            String activityName = this.getGoodsIsActivity(vo.getQueryId());
            if( activityName!= null){
                resultMap.put("activity",activityName);                       //活动标识
            }else{
                resultMap.put("activity","限时抢购");                       //活动标识
            }

        }
        return resultMap;
    }

    /**
     * 获取商品正在参与的活动
     */
    //TODO 查询商品是否参与活动， 如果商品参与活动，则显示活动价
    private String getGoodsIsActivity(Integer goodsId){

        return null;

    }


    /**
     * 获取小程序access_token
     */
    private String getAccessToken() {
        String accessToken = stringRedisTemplate.opsForValue().get(WeixinMiniproConstants.MINIPRO_ACCESS_TOKEN);
        if(accessToken == null){
            // 刷新token
            accessToken = wechatSignaturer.getCgiAccessToken(WechatTypeEnmu.MINI);
            if(accessToken == null){
                throw new RuntimeException("accessToken刷新失败，未获取到正确值");
            }
            stringRedisTemplate.opsForValue().set(WeixinMiniproConstants.MINIPRO_ACCESS_TOKEN, accessToken);
        }
        return accessToken;
    }

    private String getAccessToken1() {
        String accessToken = "33_mB172byN2zqiqHCNJnGzM-0iNJsru6M8oaGk9FF8lO5hdnZo6eM3SyyFfnTugl-wu4hfsAKBMAYSLVtlBTQdRTRIJHcklpHOncES4pExhlK5pfdy4xUfYQKKcSc0Vlf6xTZJRaInO3uGtNIMCUTbADAKCB";
        return accessToken;
    }



    /**
     * post携带json请求,并上传到oss对象服务器
     */
    public  String doPostWithJson(String reqUrl, Map<String, Object> jsonParameters) {


        try {
            URL url = new URL(reqUrl);// 创建连接
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setDoOutput(true);
            connection.setDoInput(true);
            connection.setUseCaches(false);
            connection.setInstanceFollowRedirects(true);
            connection.setRequestMethod("POST"); // 设置请求方式
            connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
            connection.connect();
            //一定要用BufferedReader 来接收响应， 使用字节来接收响应的方法是接收不到内容的
            OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
            out.append(JSONObject.fromObject(jsonParameters).toString());
            out.flush();
            out.close();
            FileDTO fileDTO = new FileDTO();
            fileDTO.setName("suncode-"+UUID.randomUUID().toString()+".jpeg");
            fileDTO.setExt("jpeg");
            fileDTO.setStream(connection.getInputStream());
            log.info("返回消息"+connection.getResponseMessage());
            log.info("访问token:"+this.getAccessToken());

            FileVO fileVO =  fileManager.upload(fileDTO,"share");
            log.info(fileVO.getUrl());
            return fileVO.getUrl();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "error"; // 自定义错误信息

    }

    /**
     * 保存海报scene的具体参数值
     * @param kvs
     * @return
     */
    @Override
    public String saveSceneDetail(Map kvs) {
        String scene = UUID.randomUUID().toString();
        cache.put("TYM_SCENE"+scene,kvs);
        return scene;
    }

    /**
     * 根据 scene 返回kvs
     * @param scene
     * @return
     */
    @Override
    public Map getSceneDetail(String scene) {
       return (Map) cache.get("TYM_SCENE"+scene);

    }

    public static void main(String[] args){
        GoodsShareManagerImpl  impl = new GoodsShareManagerImpl();
        PlacardGenVO  vo = new PlacardGenVO();
        vo.setQueryId(627);
        vo.setScene("?goods_id=627");
        vo.setPagePath("pages/goods/goods");
        impl.gen(vo);
    }
}
